﻿using System;
using TestingConcurrencyBenchmark.Helpers;

namespace TestingConcurrencyBenchmark.Problems.ProducerConsumer
{
    /// <summary>
    /// A solution for the Producer Consumer problem that contains a deadlock
    /// </summary>
    internal class ProducerConsumerWithDeadlock : AbstractProducerConsumer
    {
        private readonly BenchmarkSemaphore _mutex;

        public ProducerConsumerWithDeadlock()
        {
            _mutex = new BenchmarkSemaphore(1);
        }

        public override void Consume()
        {
            _mutex.WaitOne();
            Items.WaitOne();
            Action action = Buffer.Dequeue();
            _mutex.Release();
            action.Invoke();
        }

        public override void Produce(Action action)
        {
            _mutex.WaitOne();
            Buffer.Enqueue(action);
            _mutex.Release();
            Items.Release();
        }
    }
}